/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.modules.storage;

import java.io.IOException;

import org.anderground.core.storage.DataReader;
import org.anderground.core.storage.StorageException;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @param <T>
 *            data type
 * @param <In>
 *            the source to read the data from
 */
public abstract class AbstractReader<T, In> extends AbstractIOWrapper<In>
		implements DataReader<T> {

	@Override
	public final T read() throws IOException {
		In input = openIO();
		if (input == null) {
			throw new StorageException("openIO has returned null");
		}
		onPreExecute(input);
		try {
			T data = readFromInput(input);
			if (data == null) {
				throw new StorageException(
						"readFromInput has returned null data");
			}
			onSuccess(input);
			return data;
		} finally {
			onPostExecute(input);
			if (shouldCloseIOAfterComplete()) {
				closeIO(input);
			}
		}
	}

	/**
	 * Implementation should read a data from the specified Input.
	 * 
	 * @param in
	 *            the input to read from
	 * @return not null data instance (a {@link IOException} should be thrown
	 *         instead of returning null)
	 * 
	 * @throws IOException
	 *             (possibly wrapping another exception) if an I/O error occurs
	 */
	protected abstract T readFromInput(In in) throws IOException;

}
